<?php
namespace app\api\controller;

use app\api\controller\Base;
use think\Db;
use think\api\Client;


class Index extends Base
{
    public function _empty()
    {
        header("Location:/404.html");
        exit;
    }
    public function ajax()
    {
        $data=input('post.');
		if(!$data){
			header("Location:/404.html");
			exit;
		}
        $lizhili=Base::lizhili($data);
        if($lizhili['code']==0){
            return json(['code'=>10005,'message'=>'提交数据错误！']);
        }
        if($lizhili['code']===1){
            return ['code'=>10001,'message'=>'提交超时，请重复提交！'];
        }
        if($lizhili['code']===2){
            return ['code'=>10002,'message'=>'重复提交，请稍后重试！'];
        }
        if($lizhili['code']===4){
            return ['code'=>10004,'shua_token'=>$lizhili['data'],'shua_time'=>time()+3500];
        }
		//获取配置信息
		if($data['type']=='get_shop_info'){
			 $mall_config=Db::name('mall_config')->where('id','in',[8,9,13,18])->column('value','key');
			return ['code'=>1,'message'=>'成功','data'=>$mall_config];
		}
		
        //获取文章列表
        if ($data['type']=='get_arc_list') {
            //这里去掉了分页功能
            if ($data=Db::name('article')->where('isopen',1)->order('state desc,id desc')->where('cateid',2)->page($data['page'],8)->select()) {
                foreach ($data as &$v){
                    $v['imgs']=Db::name('article_img')->where('aid',$v['id'])->column('pic');
                    $v['ping']=Db::name('article_hui')->where('aid',$v['id'])->count();
                }
                return ['code'=>1,'message'=>'成功','data'=>$data];
            } else {
                return ['code'=>0,'message'=>'获取失败'];
            }
        }
        //获取文章详情
        if ($data['type']=='get_arc_show') {
            $info=Db::name('article')->find($data['id']);
            if ($info) {
                $w=Db::name('article_hui')->where('aid',$data['id'])->select();
                foreach ($w as &$v){
                    $u=Db::name('user')->where('id',$v['uid'])->find();
                    $v['name']= $u ? ($u['name'] ?: $u['user_no']) : "佚名";
                    $v['img']=$u ? $u['avatarUrl'] : '';
                }
                $info['ping']=$w;

                $info['goods']=Db::name('goods')->where('id',$info['goods_id'])->field('id,goods_name,goods_img')->find();

                return ['code'=>1,'message'=>'成功','data'=>$info];
            } else {
                return ['code'=>0,'message'=>'获取失败'];
            }
        }
        //获取消费商城
        if ($data['type']=='get_xiaofei_cate') {
            if($info=Db::name('goods_cate')->where('isopen',1)->select()){
                return ['code'=>1,'message'=>'成功','data'=>$info];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }
        //获取消费商城列表
        if ($data['type']=='get_xiaofei_list') {
            //分类
            if(!$data['fenlei'] or $data['fenlei']=='' or $data['fenlei']=='分类'){
                $fenlei=true;
            }else if($data['fenlei']=='其他'){
                $fenlei=[
                    ['cate_id','=',0]
                ];
            }else{
                $id=Db::name('goods_cate')->where('name',$data['fenlei'])->value('id');
                $fenlei=[
                    ['cate_id','=',$id]
                ];
            }
            //排序
            $order='is_tui desc,id desc';
            if($data['orderIndex']==1){ // 销量排序
                $order='sales_num desc';
            }
            if($data['orderIndex']==2){ //价格排序
                if($data['orderByIndex']==1){ //升序
                    $order='money asc';
                }else{
                    $order='money desc';
                }
            }
            //价格区间
            if(!$data['price1'] and !$data['price2']){
                $money=true;
            }else{
                $money=[];
                if($data['price1']){
                    $money[]=[
                        'money','>',$data['price1']
                    ];
                }
                if($data['price2']){
                    $money[]=[
                        'money','<',$data['price2']
                    ];
                }
            }
            //标签，分类 sizeSed
            if($data['sizeSed']=='0,1'){
                $w=true;
            }
            if($data['sizeSed']=='0'){
                $w[]=[
                    'lei','=',1
                ];
            }
            if($data['sizeSed']=='1'){
                $w[]=[
                    'lei','=',4
                ];
            }
            if ($info=Db::name('goods')->where($fenlei)->where($money)->where($w)->where('goods_name','like','%'.$data['key'].'%')->where('isopen',1)->order($order)->page($data['page'],16)->select()) {
                return ['code'=>1,'message'=>'成功','data'=>$info];
            } else {
                return ['code'=>0,'message'=>'已加载全部'];
            }
        }

        //首页推荐
        if($data['type']=='get_index_cate'){
            $cate=Db::name('goods_cate')->where('isopen',1)->order('sort asc')->limit(5)->select();
            $tui=Db::name('goods')->where('isopen',1)->where('is_tui',1)->limit(10)->order(true)->select();
            return ['code'=>1,'message'=>'成功','cate'=>$cate,'tui'=>$tui];
        }
        //获取幻灯片
        if ($data['type']=='get_index_swiper') {
            if ($info=Db::name('slide')->where('isopen',1)->order('sort asc')->select()) {
                $msg=Db::name('article')->where('cateid',1)->select();
                $huodong=Db::name('huodong')->select();
                return ['code'=>1,'message'=>'成功','data'=>$info,'msg'=>$msg,'huodong'=>$huodong];
            } else {
                return ['code'=>0,'message'=>'发送验证码失败'];
            }
        }

        //查看产品 分类
        if ($data['type']=='get_goods_cate') {
            $cate=Db::name('goods_cate')->where('isopen',1)->field('id as cateid,name')->order('sort asc')->select();
            $cate[]=[
                'cateid'=>0,
                'name'=>'其他'
            ];
            foreach($cate as $k=>&$v){
                $v['products']=Db::name('goods')->where('isopen',1)->where('cate_id',$v['cateid'])->field('id,goods_name,goods_img,shop_price,sales_num')->select();
            }
            return ['code'=>1,'message'=>'成功','data'=>$cate];
        }
        //产品列表
        if ($data['type']=='get_index_goods') {
            if(!isset($data['page'])){
                $data['page']=1;
            }
            //$info=Db::name('goods')->where('goods_name','like','%'.$data['key'].'%')->where('isopen',1)->order('is_tui desc,id desc')->page($data['page'],16)->select();
            $info=Db::name('goods')->where('isopen',1)->order('is_tui desc,id desc')->page($data['page'],16)->select();
            if ($info) {
                return ['code'=>1,'message'=>'成功','data'=>$info];
            } else {
                return ['code'=>0,'message'=>'已加载全部'];
            }
        }
        //产品列表
        if ($data['type']=='get_index_goods1') {
            if(!isset($data['page'])){
                $data['page']=1;
            }
            if ($info=Db::name('goods')->where('lei',1)->where('goods_name','like','%'.$data['key'].'%')->where('isopen',1)->order('is_tui desc,id desc')->select()) {
                return ['code'=>1,'message'=>'成功','data'=>$info];
            } else {
                return ['code'=>0,'message'=>'已加载全部'];
            }
        }
        //获取产品详情
        if ($data['type']=='get_index_goods_show') {
            if ($info=Db::name('goods')->where('id',$data['id'])->where('isopen',1)->find()) {
                //浏览量加一
                Db::name('goods')->where('id',$info['id'])->setInc('liu_num');
                //销量加一
                //Db::name('goods')->where('id',$info['id'])->setInc('sales_num',300);
                $attr=Db::name('goods_attr')->where('goods_id',$info['id'])->find();
                if($attr){
                    $info['attr']=array_filter(explode(",", $attr['value']));
                    $info['attrtitle']=$attr['title'];
                }else{
                    $info['attr']=[];
                    $info['attrtitle']='';
                }
				//随机推荐四个
				$tui=Db::name('goods')->where('lei',$info['lei'])->order(true)->limit(4)->select();
                return ['code'=>1,'message'=>'成功','data'=>$info];
            } else {
                return ['code'=>0,'message'=>'失败'];
            }
        }

        //发送短信
        if ($data['type']=='get_login_yzm') {
            $msg=mt_rand(111111, 999999);
            $user=\model('user');
            if ($u=Db::name('user')->where('phone', $data['phone'])->find()) {
                $user->where('id', $u['id'])->update([
                    'yzm'=>$msg
                ]);
            } else {
                $user->save([
                    'phone'=>$data['phone'],
                    'yzm'=>$msg,
                ]);
            }
            if ($this->sendsmg($data['phone'], $msg)) {
                return ['code'=>1,'message'=>'成功','data'=>$msg];
            } else {
                return ['code'=>0,'message'=>'发送验证码失败'];
            }
        }
        //手机注册
        if ($data['type']=='phone_login') {
            $info=\json_decode($data['data'], true);
            $f_user=Db::name('user')->where('user_no',$info['user_no'])->find();
            // if(!$f_user){
            //     return ['code'=>0,'message'=>'邀请码不正确'];
            // }
            if(!$info['password']){
                return ['code'=>0,'message'=>'请填写密码'];
            }
            if ($wo=Db::name('user')->where('phone', $info['phoneno'])->where('yzm',$info['pwd'])->where('isopen',1)->find()) {
                if (!$wo['user_no']) {
					$user_no=$this->sui($wo['id']);
                    Db::name('user')->where('id', $wo['id'])->update(['user_no'=>$user_no]);
                }else{
					$user_no=$wo['user_no'];
				}
                if (!$wo['fid'] and $f_user) {
                    Db::name('user')->where('id', $wo['id'])->update(['fid'=>$f_user['id']]);
					//设置身份
					if($f_user['shenfen']==1){
						 Db::name('user')->where('id', $wo['id'])->update(['shenfen'=>2]);
					}
                }
                $token=md5(time()).$wo['id'];
                Db::name('user')->where('id', $wo['id'])->update(['token'=>$token,'password'=>md5(sha1($info['password']))]);
                return ['code'=>1,'message'=>'登陆成功','data'=>$token,'uid'=>$wo['id'],'user_no'=>$user_no];
            } else {
                return ['code'=>0,'message'=>'手机或验证码不正确'];
            }
        }
        //手机找回密码
        if ($data['type']=='phone_login_zhao') {
            $info=\json_decode($data['data'], true);
            if(!$info['password']){
                return ['code'=>0,'message'=>'请填写密码'];
            }
            if ($wo=Db::name('user')->where('phone', $info['phoneno'])->where('yzm',$info['pwd'])->where('isopen',1)->find()) {
                if(!$wo['password']){
                    return ['code'=>0,'message'=>'尚未注册，请注册后登陆'];
                }
				if (!$wo['user_no']) {
					$user_no=$this->sui($wo['id']);
				    Db::name('user')->where('id', $wo['id'])->update(['user_no'=>$user_no]);
				}else{
					$user_no=$wo['user_no'];
				}
				
                $token=md5(time()).$wo['id'];
                Db::name('user')->where('id', $wo['id'])->update(['token'=>$token,'password'=>md5(sha1($info['password']))]);
                return ['code'=>1,'message'=>'登陆成功','data'=>$token,'uid'=>$wo['id'],'user_no'=>$user_no];
            } else {
                return ['code'=>0,'message'=>'手机或验证码不正确'];
            }
        }

        //手机登陆
        if ($data['type']=='phone_login_login') {
            $info=\json_decode($data['data'], true);
            if ($wo=Db::name('user')->where('phone', $info['phoneno'])->where('password',md5(sha1($info['password'])))->where('isopen',1)->find()) {
                if (!$wo['user_no']) {
                    return ['code'=>0,'message'=>'未注册'];
                }
                $token=md5(time()).$wo['id'];
                Db::name('user')->where('id', $wo['id'])->update(['token'=>$token]);
                return ['code'=>1,'message'=>'登陆成功','data'=>$token,'uid'=>$wo['id'],'user_no'=>$wo['user_no']];
            } else {
                return ['code'=>0,'message'=>'手机或密码不正确'];
            }
        }
        //说明列表
        if ($data['type']=='get_xiangguan_list') {
            $res=Db::name('shuoming')->where('isopen',1)->select();
            if($res){
                return ['code'=>1,'message'=>'成功','data'=>$res];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }
        //获取相关
        if ($data['type']=='get_xiangguan') {
            $arr1=explode('_',$data['lei']);
            if($arr1[0]=='tongzhi'){
                $res=Db::name('article')->find($arr1[1]);
            }else{
                $res=Db::name('shuoming')->find($data['lei']);
            }
            if($res){
                return ['code'=>1,'message'=>'成功','data'=>$res];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }
        //app  升级
        if ($data['type']=='update_app') {
            $config=Db::name('mall_update')->where('isopen',1)->order('app_v desc')->find();
            if($config){
                return ['code'=>1,'app_v'=>$config['app_v'],'url'=>'http://'.\request()->host().'/update/update_'.$config['app_v'].'.apk','desc'=>$config['desc']];
            }
            return ['code'=>0];
        }
        //查看是否有权限
        if ($data['type']=='get_my_check') {
            if($user=Db::name('user')->where('token',$data['token'])->where('isopen',1)->find()){
                return ['code'=>1,'message'=>'成功','token'=>$user['token'],'uid'=>$user['id'],'user_no'=>$user['user_no']];
            }else{
                return ['code'=>0,'message'=>'失败'];
            }
        }
		//微信获取openid
		if ($data['type']=='get_wx_openid') {
		    $raw=\json_decode($data['rawData'],true);
			$config=Db::name('mall_config')->column('value','key');
		    $appid=$config['wx_xcx_appid'];
		    $secret=$config['wx_xcx_secret'];
		    $code=$this->curl('https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$data['code'].'&grant_type=authorization_code');
		    if($code and $raw){
		        $raw['openid']=$code['openid'];
		        if($user=Db::name('user')->where('token',$data['token'])->find()){
		            Db::name('user')->where('id',$user['id'])->update(['openid_wx'=>$code['openid']]);
		            return ['code'=>1,'message'=>'已经绑定微信'];
		        }
				return ['code'=>0,'message'=>'获取用户信息失败'];
		    }else{
		        return ['code'=>0,'message'=>'登陆失败'];
		    }
		}
        //微信登陆
        if ($data['type']=='get_login_wx_user') {
			$f_user=Db::name('user')->where('user_no',$data['user_no'])->find();
			// if(!$f_user){
			//     return ['code'=>0,'message'=>'邀请码不正确,请使用正确链接登陆'];
			// }
            $raw=\json_decode($data['rawData'],true);
            $config=Db::name('mall_config')->column('value','key');
            $appid=$config['wx_xcx_appid'];
            $secret=$config['wx_xcx_secret'];
            $code=$this->curl('https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$data['code'].'&grant_type=authorization_code');
            if($code and $raw){
                $raw['openid']=$code['openid'];
                if($user=Db::name('user')->where('openid_wx',$code['openid'])->find()){
                    $token=md5($user['openid_wx'].time());
                    Db::name('user')->where('id',$user['id'])->update(['token'=>$token,'openid_wx'=>$code['openid']]);
					//设置上一级
					if (!$user['fid'] and $f_user) {
					    Db::name('user')->where('id', $wo['id'])->update(['fid'=>$f_user['id']]);
						//设置身份
						if($f_user['shenfen']==1){
							 Db::name('user')->where('id', $wo['id'])->update(['shenfen'=>2]);
						}
					}
					
                    return ['code'=>1,'message'=>'已经绑定微信','token'=>$token,'uid'=>$user['id'],'user_no'=>$user['user_no']];
                }else{
                    $raw['token']=md5($raw['openid'].time());
                    $linshi=\model('user');
                    $raw['openid_wx']=$raw['openid'];
                    $raw['unionid']=isset($code['unionid']) ? $code['unionid'] : '';
                    $linshi->save($raw);
					//设置上一级
					if ($f_user) {
					    Db::name('user')->where('id', $linshi->id)->update(['fid'=>$f_user['id']]);
						//设置身份
						if($f_user['shenfen']==1){
							 Db::name('user')->where('id', $linshi->id)->update(['shenfen'=>2]);
						}
					}
					$user_no=$this->sui($linshi->id);
                    Db::name('user')->where('id',$linshi->id)->update(['user_no'=>$user_no]);
                    return ['code'=>1,'message'=>'已经绑定微信','token'=>$raw['token'],'uid'=>$linshi->id,'user_no'=>$user_no];
                }
            }else{
                return ['code'=>0,'message'=>'登陆失败'];
            }
        }
        //微信登陆 app登陆
        if ($data['type']=='get_login_wx_app') {
			$f_user=Db::name('user')->where('user_no',$data['user_no'])->find();
			// if(!$f_user){
			//     return ['code'=>0,'message'=>'邀请码不正确,请使用正确链接登陆'];
			// }
            $info=\json_decode($data['info'],true);
            if($info['unionId']){
                if($user=Db::name('user')->where('unionId',$info['unionId'])->find()){
                    $token=md5($user['openid_app'].time());
                    Db::name('user')->where('id',$user['id'])->update(['token'=>$token,'openid_app'=>$info['openId']]);
                   //设置上一级
                   if (!$user['fid'] and $f_user) {
                       Db::name('user')->where('id', $wo['id'])->update(['fid'=>$f_user['id']]);
                   	//设置身份
                   	if($f_user['shenfen']==1){
                   		 Db::name('user')->where('id', $wo['id'])->update(['shenfen'=>2]);
                   	}
                   }
                    return ['code'=>1,'message'=>'已经绑定微信','token'=>$token,'uid'=>$user['id'],'user_no'=>$user['user_no']];
                }else{
                    $raw=[];
                    $raw['token']=md5($info['openId'].time());
                    $linshi=\model('user');
                    $raw['openid_app']=$info['openId'];
                    $raw['nickName']=$info['nickName'];
                    $raw['gender']=$info['gender'];
                    $raw['city']=$info['city'];
                    $raw['province']=$info['province'];
                    $raw['country']=$info['country'];
                    $raw['avatarUrl']=$info['avatarUrl'];
                    $raw['unionId']=$info['unionId'];
                    $linshi->save($raw);
                    //设置上一级
                    if ($f_user) {
                        Db::name('user')->where('id', $linshi->id)->update(['fid'=>$f_user['id']]);
                    	//设置身份
                    	if($f_user['shenfen']==1){
                    		 Db::name('user')->where('id', $linshi->id)->update(['shenfen'=>2]);
                    	}
                    }
					$user_no=$this->sui($linshi->id);
                    Db::name('user')->where('id',$linshi->id)->update(['user_no'=>$user_no]);
                    return ['code'=>1,'message'=>'已经绑定微信','token'=>$raw['token'],'uid'=>$linshi->id,'user_no'=>$user_no];
                }
            }else{
                return ['code'=>0,'message'=>'登陆失败'];
            }
        }
        return ['code'=>0,'message'=>'非法获取'];
    }
    private function sui($id=0)
    {
        $str=[
            0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        ];
        $sui='';
        for ($i=0;$i<5;$i++) {
            $sui.=$str[mt_rand(0, 35)];
        }

        return $sui.$id;
    }
    private function sendsmg($phone, $msg)
    {
        $config=Db::name('mall_config')->column('value','key');
        $client = new Client($config['think_secret']);
        $result = $client->smsSend()
            ->withSignId($config['think_qian'])
            ->withTemplateId($config['think_moban'])
            ->withPhone($phone)
            ->withParams('{"code": "'.$msg.'"}')
            ->request();
        if($result){
            return true;
        }
        return false;
    }
	
}
